import java.io.IOException;
import java.net.*;
import java.util.Scanner;

public class EdpChoClient {
    private DatagramSocket socket = null;
    private String IP;
    private int Port;
    public EdpChoClient(String ip,int port) throws SocketException {
        socket = new DatagramSocket();
        this.IP = ip;
        this.Port = port;
    }
    public void start() throws IOException {
        System.out.println("客户端启动");
        Scanner scanner = new Scanner(System.in);
        while (true){
            //输入要传输的内容
            String request = scanner.next();
            //创建DatagramPacket来储存数据 字节数组，数组长度,IP地址和端口号
            DatagramPacket requestpacket = new DatagramPacket(request.getBytes(),request.getBytes().length, InetAddress.getByName(this.IP),this.Port);
            //发送数据
            socket.send(requestpacket);
            DatagramPacket responsePacket = new DatagramPacket(new byte[1024],1024);
            //接收客户端处理后的消息
            socket.receive(responsePacket);
            //转化为 String 类型
            String response = new String(responsePacket.getData(),0,responsePacket.getLength());
            //打印
            System.out.println(response);
        }
    }

    public static void main(String[] args) throws IOException {
        EdpChoClient client = new EdpChoClient("127.0.0.1",1010);
        client.start();
    }
}
